package com.elean.pms.common;


import com.elean.pms.utils.JsonUtils;
import com.elean.pms.utils.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: 周作为
 * @Date: 2019/9/27 17:22
 * @Description:
 */
@Aspect
@Component
public class NoRepeatSubmitAop {


    @Autowired
    private RedisUtil redisUtil;



    @Pointcut("@annotation(com.elean.pms.common.NoRepeatSubmit)")
    public void annotationPointCut(){

    }


    @Around("annotationPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(Global.AUTHORIZE_TOKEN);
        String key = token + "-" + request.getServletPath()+ JsonUtils.obj2String(request.getParameterMap());
        if (redisUtil.get(key) == null) {

            System.out.println("======目标方法执行之前======");
            Object o = joinPoint.proceed();
            System.out.println("=======目标方法执行之后======");
            // 2秒内统一用户同一个地址同一个参数，视为重复提交
            redisUtil.set(key, "0",Global.NO_SUBMIT_TIME);
            return o;
        } else {
            return ResponseEntity.buildCodes(StatusCode.REPEAT_SUMBIT, CommonErrorCodes.REPEAT_SUBMIT);
        }
    }



}
